//
//  MediaSourceController.m
//  yameishe3
//
//  Created by pro on 2017/3/7.
//  Copyright © 2017年 yameishe. All rights reserved.
//

#import "MediaSourceController.h"
#import "RangeWebsiteController.h"
#import "NewsReleaseController.h"
#import "WJDropdownMenu.h"
#import "SourceCell.h"
#import "SelectView.h"
#import "JSONKit.h"
#import "NetworkManager.h"
#import "YMSMediaSource.h"
#define selectViewH ScreenHeight/2.0-50
@interface MediaSourceController ()<WJMenuDelegate,UITableViewDelegate,UITableViewDataSource>
{
    NSInteger page;
    NSMutableArray *_sourcrArray;
    NSMutableArray *_conditionArray;
    NSMutableArray *_conditionTypeArray;
    NSMutableArray *_selectSourceArray;
    NSMutableDictionary *_basicDic;
    __weak IBOutlet UIView *_maskView;
    __weak IBOutlet UIView *_bottomView;
    __weak IBOutlet UILabel *_selectCountLab;
    
    SelectView *_selectView;
}
@property (nonatomic,weak)WJDropdownMenu *menu;
@property (nonatomic,weak)IBOutlet UITableView *tableView;

@end

@implementation MediaSourceController

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    self.view.backgroundColor = [UIColor redColor];
    // Do any additional setup after loading the view.
    [self controllerSetting];
    _sourcrArray = [[NSMutableArray alloc]init];
    _conditionArray = [[NSMutableArray alloc]init];
    _selectSourceArray = [[NSMutableArray alloc]init];
   
    _tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 50)];
    [_tableView registerNib:[UINib nibWithNibName:@"SourceCell"bundle:nil] forCellReuseIdentifier:@"SourceCell"];
    
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(50+64);
        make.leading.trailing.bottom.equalTo(self.view);
    }];
    [_bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.view).offset(50);
        make.leading.trailing.bottom.equalTo(self.view);
    }];
    [_maskView addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onTouchMaskView)]];
    
    
    WJDropdownMenu *menu = [[WJDropdownMenu alloc]initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, 40)];
    menu.delegate = self;         //  设置代理
    [self.view insertSubview:menu belowSubview:_maskView ];
    self.menu = menu;
    
    [self.menu mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(64);
        make.leading.trailing.equalTo(self.view);
        make.height.equalTo(@(50));
    }];
    [self setMenuDetail];
    [self requestCondition];
    
    _selectView = [[[NSBundle mainBundle]loadNibNamed:@"SelectView" owner:self options:nil] firstObject];
    [self.view addSubview:_selectView];
    [_selectView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_bottom);
        make.leading.trailing.equalTo(self.view);
        make.height.equalTo(@(selectViewH));
    }];
    __weak typeof(self) wself = self;
    [_selectView setCallbackDidChangeArray:^(NSArray *array) {
        [wself.tableView reloadData];
    }];
   
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    [self.view layoutIfNeeded];
     self.tabBarController.tabBar.hidden=YES;
//    self.hidesBottomBarWhenPushed = YES; 
    
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    self.tabBarController.tabBar.hidden=YES;
//    self.hidesBottomBarWhenPushed = YES;
    
}
-(void)onTouchMaskView
{
    [self onTouchShowSelectView:NO];
}
-(void)requestCondition
{
    page = 1;
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setValue:[YMSMember loginMember].token forKey:@"_token"];
    _basicDic = [[NSMutableDictionary alloc]init];
    [_basicDic setValue:@"0" forKey:@"keyword"];
    [_basicDic setValue:@(page) forKey:@"page"];
   [[NetworkManager alloc] getConditionWithDic:dic successBlock:^(NSDictionary *result) {
       if (result) {
           _conditionArray = result[@"data"];
           _conditionTypeArray = [[NSMutableArray alloc]init];
           NSMutableArray *basicConditionArray = [[NSMutableArray alloc]init];
           for (int i = 0; i<_conditionArray.count; i++) {
               NSMutableDictionary *categoryDic = _conditionArray[i];
               [_conditionTypeArray addObject:categoryDic[@"name"]];
               NSMutableDictionary* dic = [[NSMutableDictionary alloc]init];
               [dic setValue:categoryDic[@"category_id"] forKey:@"category_id"];
               [dic setValue:@"0" forKey:@"data_id"];
               [basicConditionArray addObject:dic];
           }
           [_basicDic setValue:basicConditionArray forKey:@"data"];
           [self requestMediaData];
           [self createAllMenuData];
       }
   } failureBlock:^(NSString *error) {
    
   }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)setMenuDetail
{
    self.menu.caverAnimationTime = 0.2;             //  增加了展开动画时间设置   不设置默认是  0.15
    self.menu.hideAnimationTime = 0.2;              //  增加了缩进动画时间设置   不设置默认是  0.15
    self.menu.menuTitleFont = 12;                   //  设置menuTitle字体大小    不设置默认是  11
    self.menu.tableTitleFont = 11;                  //  设置tableTitle字体大小   不设置默认是  10
    self.menu.cellHeight = 38;                      //  设置tableViewcell高度   不设置默认是  40
    self. menu.menuArrowStyle = menuArrowStyleSolid; //  旋转箭头的样式(空心箭头 or 实心箭头)
    self. menu.tableViewMaxHeight = 200;             //  tableView的最大高度(超过此高度就可以滑动显示)
    self.menu.menuButtonTag = 100;                  //  menu定义了一个tag值如果与本页面的其他button的值有冲突重合可以自定义设置
    self.menu.CarverViewColor = [UIColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:0.5];//设置遮罩层颜色
    self.menu.selectedColor = [UIColor redColor];   //  选中的字体颜色
    self.menu.unSelectedColor = [UIColor grayColor];//  未选中的字体颜色
    
    
}
- (void)createAllMenuData{
    NSArray *TitleArray =  @[@"筛选"];
    //  创建第一个菜单的first数据second数据
//    NSArray *firstArrOne = [NSArray arrayWithObjects:@"网站类型",@"入口级别",@"入口形式",@"覆盖区域",@"频道类型",@"会员价", nil];
    NSArray *firstArrOne = [NSArray arrayWithArray:_conditionTypeArray];
    NSArray *firstMenu = [NSArray arrayWithObject:firstArrOne];
    
    [self.menu createOneMenuTitleArray:TitleArray FirstArray:firstMenu];
}
- (void)hideMenu{
    //  点击收缩menu
    [self.menu drawBackMenu];
}
#pragma mark -- WJMenuDelegate
-(void)menuCellDidSelected:(NSInteger)MenuTitleIndex firstIndex:(NSInteger)firstIndex andSecondIndex:(NSInteger)secondIndex
{
    RangeWebsiteController *vc = [[UIStoryboard storyboardWithName:@"Range" bundle:nil] instantiateViewControllerWithIdentifier:@"RangeWebsiteController"];
    vc.dataArray = _conditionArray[firstIndex][@"data"];
    vc.conditionDic = _conditionArray[firstIndex];
    [self.navigationController pushViewController:vc animated:YES];
    
    [vc setCallbackDidSelect:^(NSDictionary *conditionDic, NSDictionary *dataDic) {
        NSMutableArray *array = _basicDic[@"data"];
        for (int i = 0; i<array.count; i++) {
            NSMutableDictionary *dic = array[i];
            if ([dic[@"category_id"] isEqualToString:conditionDic[@"category_id"]]) {
                [dic setValue:dataDic[@"id"] forKey:@"data_id"];
                [array replaceObjectAtIndex:i withObject:dic];
            }
        }
        [_basicDic setValue:array forKey:@"data"];
        [_basicDic setValue:@"1" forKey:@"keyword"];
        [self requestMediaData];
    }];
    
}
-(NSMutableDictionary*)getSubmitDic
{
    NSMutableDictionary *basicdic = [[NSMutableDictionary alloc]initWithDictionary:_basicDic];
    NSArray *array = basicdic[@"data"];
    NSMutableArray *resultArray = [[NSMutableArray alloc]init];
    for (int i = 0; i<array.count; i++) {
        NSDictionary *dic = array[i];
        NSString *str = [NSString stringWithFormat:@"%@,%@",dic[@"category_id"],dic[@"data_id"]];
        [resultArray addObject:str];
    }
    [basicdic setObject:resultArray forKey:@"data"];
    return basicdic;
}
-(void)requestMediaData
{
    [_basicDic setValue:[YMSMember loginMember].token forKey:@"_token"];
    
    NSString * json = [_basicDic jsonString];
   
   [[NetworkManager alloc]getMediaSourceWithDic:[self getSubmitDic] successBlock:^(NSArray *result) {
       _sourcrArray = [[NSMutableArray alloc]initWithArray:result];
       [_tableView reloadData];
   } failureBlock:^(NSString *error) {
    
   }];
}
-(void)onTouchShowSelectView:(BOOL)show
{
    if (show == YES) {
        [UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
            [_selectView mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.bottom.equalTo(self.view.mas_bottom).offset(-50);
                make.leading.trailing.equalTo(self.view);
                make.height.equalTo(@(selectViewH));
            }];
            
           _maskView.alpha = _selectView.alpha = 1;
        } completion:nil];
    }
    else
    {
        [UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
            [_selectView mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(self.view.mas_bottom);
                make.leading.trailing.equalTo(self.view);
                make.height.equalTo(@(selectViewH));
            }];
            _maskView.alpha = _selectView.alpha = 0;
        } completion:nil];

    }
}

-(IBAction)onTouchBottom:(UIButton*)sender
{
    if (_maskView.alpha == 1) {
        [self onTouchShowSelectView:NO];
    }
    else
    {
        [self onTouchShowSelectView:YES];
    }
}

#pragma mark -- UITableViewDataSource,UITableViewDelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//    return 10;
     _selectCountLab.text = [NSString stringWithFormat:@"%ld",_selectSourceArray.count];
    return _sourcrArray.count;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SourceCell* cell = [tableView dequeueReusableCellWithIdentifier:@"SourceCell"];
//    [cell setTitle:_typeArray[indexPath.row]];
    cell.source = _sourcrArray[indexPath.row];
    cell.backgroundColor = [UIColor whiteColor];
    if ([_selectSourceArray containsObject:_sourcrArray[indexPath.row]]) {
        cell.backgroundColor = [UIColor yellowColor];
    }
    
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 200;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    YMSMediaSource *source = _sourcrArray[indexPath.row];
    if ([_selectSourceArray containsObject:source]) {
        [_selectSourceArray removeObject:source];
    }
    else{
        [_selectSourceArray addObject:source];
    }
    [_tableView reloadRow:indexPath.row inSection:indexPath.section withRowAnimation:UITableViewRowAnimationNone];
    _selectView.selectArray = _selectSourceArray;
    _selectCountLab.text = [NSString stringWithFormat:@"%ld",_selectSourceArray.count];
}

-(IBAction)onTouchNextStep:(id)sender
{
    if (_selectSourceArray.count == 0) {//没有选择任何媒体资源
        return;
    }
    if ([_type isEqualToString:@"NewsReleaseController"]) {
        NewsReleaseController *vc = [[UIStoryboard storyboardWithName:@"Network" bundle:nil] instantiateViewControllerWithIdentifier:@"NewsReleaseController"];
        [self.navigationController pushViewController:vc animated:YES];

    }
}

@end
